package com.example.epidemic_assistant.ui.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.android.epidemic_assistant.gen.DaoSession;
import com.android.epidemic_assistant.gen.UserBeanDao;
import com.bumptech.glide.Glide;
import com.example.epidemic_assistant.App;
import com.example.epidemic_assistant.R;
import com.example.epidemic_assistant.bean.UserBean;
import com.example.epidemic_assistant.ui.PeopleVisitedActivity;
import com.example.epidemic_assistant.ui.PlacesVisitedActivity;
import com.example.epidemic_assistant.util.FileUtil;
import com.example.epidemic_assistant.util.GlideEngine;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_CANCELED;
import static android.content.Context.MODE_PRIVATE;

/**
 * 信息 - 碎片
 */
public class InfoFragment extends Fragment {

    private static final String TAG = "InfoFragment";

    private EditText mEdtName;
    private EditText mEdtAge;
    private EditText mEdtSex;
    private EditText mEdtIdCard;
    private EditText mEdtAddress;
    private EditText mEdtPlace;
    private EditText mEdtPeople;
    private Button mBtnAddPlace;
    private Button mBtnAddPeople;
    private Button mBtnSure;
    private Button mBtnCancel;
    private Button mBtnCheckPlace;
    private Button mBtnCheckPeople;
    private ImageView mImgHealth;
    private ImageView mImgHealthMa;
    private Spinner mSpinnerPlace;
    private Spinner mSpinnerPeople;

    private String mUsername;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;

    private List<String> mPlaces;
    private List<String> mPeople;

    private ArrayList<String> mPlaceList = new ArrayList<>();
    private ArrayList<String> mPeopleList = new ArrayList<>();

    private App mMyApp;
    private DaoSession mDaoSession;
    private UserBeanDao mUserBeanDao;
    private UserBean mUserBean;
    private String mSelectPlaceData;
    private String mSelectPeopleData;
    private String[] mStringPlaceArray;
    private String[] mStringPeopleArray;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_info, container, false);

        initView(view);
        initData();
        initListener();

        return view;
    }

    private void initListener() {
        mBtnAddPlace.setOnClickListener(view -> {
            String place = mEdtPlace.getText().toString().trim();
            checkNull(place);
            mPlaceList.add(mSelectPlaceData + " - " + place);
            mUserBean.setPlaces(mPlaceList);
            mUserBeanDao.update(mUserBean);
        });
        mBtnAddPeople.setOnClickListener(view -> {
            String people = mEdtPeople.getText().toString().trim();
            checkNull(people);
            mPeopleList.add(mSelectPeopleData + " - " + people);
            mUserBean.setPeople(mPeopleList);
            mUserBeanDao.update(mUserBean);
        });

        mBtnSure.setOnClickListener(view -> {
            String name = mEdtName.getText().toString().trim();
            String age = mEdtAge.getText().toString().trim();
            String sex = mEdtSex.getText().toString().trim();
            String card = mEdtIdCard.getText().toString().trim();
            String address = mEdtAddress.getText().toString().trim();
            checkNull(name);
            checkNull(age);
            checkNull(sex);
            checkNull(card);
            checkNull(address);
            mUserBean.setName(name);
            mUserBean.setAge(age);
            mUserBean.setSex(sex);
            mUserBean.setIdCard(card);
            mUserBean.setFamilyAddress(address);
            mUserBeanDao.update(mUserBean);
            Toast.makeText(requireContext(), "保存成功", Toast.LENGTH_SHORT).show();
        });
        mBtnCancel.setOnClickListener(view -> {
            mEdtName.setText("");
            mEdtAge.setText("");
            mEdtSex.setText("");
            mEdtIdCard.setText("");
            mEdtAddress.setText("");
        });
        mBtnCheckPlace.setOnClickListener(view -> {
            startActivity(new Intent(getActivity(), PlacesVisitedActivity.class));
        });
        mBtnCheckPeople.setOnClickListener(view -> {
            startActivity(new Intent(getActivity(), PeopleVisitedActivity.class));
        });

        mSpinnerPlace.setSelection(2);
        mSpinnerPeople.setSelection(2);
        mSelectPlaceData = mStringPlaceArray[2];
        mSelectPeopleData = mStringPeopleArray[2];
        mSpinnerPlace.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                mSelectPlaceData = mStringPlaceArray[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        mSpinnerPeople.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                mSelectPeopleData = mStringPeopleArray[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        mImgHealth.setOnClickListener(view -> {
            EasyPhotos.createAlbum(InfoFragment.this, true,false,
                    GlideEngine.getInstance()).setFileProviderAuthority("com.example" +
                    ".epidemic_assistant.fileprovider").start(0);
        });
        mImgHealthMa.setOnClickListener(view -> {
            EasyPhotos.createAlbum(InfoFragment.this, true,false,
                    GlideEngine.getInstance()).setFileProviderAuthority("com.example" +
                    ".epidemic_assistant.fileprovider").start(1);
        });
    }

    private void initData() {

        mSharedPreferences = getActivity().getSharedPreferences("autoLogin", MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        String username = mSharedPreferences.getString("username", "");
        if (!username.isEmpty()) {
            mUsername = username;
        } else {
            mUsername = getActivity().getIntent().getExtras().getString("username");
        }

        mMyApp = (App) getActivity().getApplication();
        mDaoSession = mMyApp.getDaoSession();
        mUserBeanDao = mDaoSession.getUserBeanDao();
        List<UserBean> userBeanList = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserName.eq(mUsername)).list();
        for (int i = 0; i < userBeanList.size(); i++) {
            UserBean userBean = userBeanList.get(i);
            if (userBean.getUserName().equals(username)) {
                mUserBean = userBean;
            }
        }
        if (mUserBean != null) {
            mEdtName.setText(mUserBean.getName());
            mEdtAge.setText(mUserBean.getAge());
            mEdtSex.setText(mUserBean.getSex());
            mEdtIdCard.setText(mUserBean.getIdCard());
            mEdtAddress.setText(mUserBean.getFamilyAddress());
            if (mUserBean.getHealthImgPath() != null) {
                mImgHealth.setImageBitmap(FileUtil.ImagePathToBitmap(mUserBean.getHealthImgPath()));
            }
            if (mUserBean.getHealthMaImgPath() != null) {
                mImgHealthMa.setImageBitmap(FileUtil.ImagePathToBitmap(mUserBean.getHealthMaImgPath()));
            }
            if (mUserBean.getPlaces() != null) {
                mPlaces = mUserBean.getPlaces();
                mPlaceList.addAll(mPlaces);
            }

            if (mUserBean.getPeople() != null) {
                mPeople = mUserBean.getPeople();
                mPeopleList.addAll(mPeople);
            }
        }

        mStringPlaceArray = getResources().getStringArray(R.array.data_array);
        mStringPeopleArray = getResources().getStringArray(R.array.data_array);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (data != null) {
                ArrayList<Photo> photos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                if (photos != null) {
                    mUserBean.setHealthImgPath(photos.get(0).path);
                    mUserBeanDao.update(mUserBean);
                    Glide.with(this).load(photos.get(0).uri).into(mImgHealth);
                }
            }
        } else if (requestCode == 1) {
            if (data != null) {
                ArrayList<Photo> photos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                if (photos != null) {
                    mUserBean.setHealthMaImgPath(photos.get(0).path);
                    mUserBeanDao.update(mUserBean);
                    Glide.with(this).load(photos.get(0).uri).into(mImgHealthMa);
                }
            }
        } else if (RESULT_CANCELED == resultCode) {
            Toast.makeText(requireContext(), getString(R.string.cancel), Toast.LENGTH_SHORT).show();
        }
    }

    private void initView(View view) {
        mEdtName = view.findViewById(R.id.edt_name);
        mEdtAge = view.findViewById(R.id.edt_age);
        mEdtSex = view.findViewById(R.id.edt_sex);
        mEdtIdCard = view.findViewById(R.id.edt_card);
        mEdtAddress = view.findViewById(R.id.edt_address);
        mEdtPlace = view.findViewById(R.id.edt_place);
        mEdtPeople = view.findViewById(R.id.edt_people);
        mBtnAddPlace = view.findViewById(R.id.btn_add_place);
        mBtnAddPeople = view.findViewById(R.id.btn_add_people);
        mBtnSure = view.findViewById(R.id.btn_sure);
        mBtnCancel = view.findViewById(R.id.btn_cancel);
        mBtnCheckPlace = view.findViewById(R.id.btn_check_place);
        mBtnCheckPeople = view.findViewById(R.id.btn_check_people);
        mSpinnerPlace = view.findViewById(R.id.spinner_place);
        mSpinnerPeople = view.findViewById(R.id.spinner_people);
        mImgHealth = view.findViewById(R.id.img_health);
        mImgHealthMa = view.findViewById(R.id.img_health_ma);
    }

    private void checkNull(String string) {
        if (string.isEmpty()) {
            Toast.makeText(requireContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
        }
    }
}